import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:gold/app/order_event.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/apis.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/my/order/order_config.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/dialog/refund_reason_dialog.dart';

/// @description:
/// @author tangzhentao
/// @created at 13:27 2024/12/14

class ApplyRefundViewmodel extends Viewmodel {
  /// 订单信息
  final OrderModel order;

  /// 添加图片数据
  final _addPhoto = AddPhoto(File(Res.imagesRefundPhoto), isAdd: true);
  /// 添加图片
  List<AddPhoto> photos = [];

  /// 补充描述
  final TextEditingController controller = TextEditingController();
  final FocusNode focusNode = FocusNode();

  RefundReason? _reason;
  /// 退款原因
  RefundReason? get reason => _reason;
  set reason(RefundReason? value) {
    hideKeyboard();
    if (_reason != value) {
      _reason = value;
      notifyListeners();
    }
  }

  int _length = 0;
  /// 退款原因
  int get length => _length;
  set length(int value) {
    if (_length != value) {
      _length = value;
      notifyListeners();
    }
  }

  ApplyRefundViewmodel(this.order) {
    photos.add(_addPhoto);
  }

  Future pickRefundReason() async {
    final result = await showRefundReasonDialog(reason: _reason);
    if (result != null) {
      reason = result;
    }
  }

  /// 添加照片
  Future addPhoto() async {
    final needCount = 3 - (photos.length - 1);
    final files = await pickPhoto(max: needCount);
    if (files?.isNotEmpty == true) {
      if (needCount == files!.length) {
        photos.removeLast();
        photos.insertAll(0, files.map((file) => AddPhoto(file)).toList());
      } else {
        photos.removeLast();
        photos.insertAll(0, files.map((file) => AddPhoto(file)).toList());
        photos.add(_addPhoto);
      }
      setSuccessChange();
    }
  }

  /// 添加照片
  void deletePhoto(int index) {
    photos.removeAt(index);
    if (!photos.last.isAdd) {
      photos.add(_addPhoto);
    }
    setSuccessChange();
  }

  /// 提交
  Future submit() async {
    if (_reason == null) {
      '请选择退款原因'.info();
      return;
    }
    if (controller.text.isEmpty) {
      '请输入评价内容'.info();
      return;
    }
    String uploadResult = '';
    final List<String> images = [];
    if (photos.length > 1) {
      await Future.forEach(photos, (add) async {
        if (!add.isAdd) {
          if (add.http.isEmpty) {
            final data = await compressImage(await add.file.readAsBytes());
            final file = MultipartFile.fromBytes(data, filename: '${DateTime.now().millisecondsSinceEpoch}.png');
            final formData = FormData.fromMap({'file' : file});
            final result = await Http().uploadImage<String>(Apis.upload, formData, showErrorMsg: false);
            if (result.success && result.data?.isNotEmpty == true) {
              add.http = '${Apis.imageBaseUrl}${result.data!}';
              images.add(result.data!);
            } else {
              uploadResult = result.msg;
            }
          } else {
            images.add(add.http.replaceAll(Apis.imageBaseUrl, ''));
          }
        }
      });
    }
    if (uploadResult.isNotEmpty) {
      uploadResult.error();
      return;
    }
    final result = await Http().request<dynamic>(ApiOrder.refundCreate, data: {
      'order_id': order.id, 'price': (order.payPrice?? 0.00) + (order.amountNum?? 0.00), 'type': 0,
      'reason': _reason?.reason, 'images': images.join(','),
    }, loadingText: '申请退款中...', successText: '已申请');
    if (result.success) {
      XfgNav.pop();
      XfgNav.eventBus.fire(ApplyingRefundOrder(order.id!));
    }
  }

  @override
  void dispose() {
    controller.dispose();
    focusNode.dispose();
    super.dispose();
  }
}

class AddPhoto {
  final bool isAdd;
  final File file;
  String http;

  AddPhoto(this.file ,{this.http = '', this.isAdd = false});
}
